#include "util.h"
#include <stdlib.h>
#include <omp.h>
#define PASSO 14

int main(int argc, char *argv[]) {

  info *sistema;

  int iter = 0;
  int i, j;
  int continua = 1;

  double *X, *Xk;
  double **A;
  double *b;

  double start_time;

  printf("...Collecting information in the file %s...\n",argv[1]);
  sistema = createInfo(argv[1]);

  if(sistema == NULL)
    return EXIT_FAILURE;

  printf("...Creating matrix A...\n");
  A = getMatrixA(sistema);
  printf("...Creating matrix b...\n");
  b = getMatrixB(sistema);

  printf("...Allocating memory for solver...\n");
  X = (double *)malloc(sistema->order*sizeof(double));
  Xk = (double *)malloc(sistema->order*sizeof(double));

  for(i=0;i<sistema->order;i++) {
    X[i] = 0.0;
    Xk[i] = 0.0;
  }
 
  printf("...Starting linear solving...\n");
  start_time = omp_get_wtime();
  do {
//    printf("...Iter %d...\n",iter);

    for(i=0;i<sistema->order;i++) {
      Xk[i] = 0.0;
      for(j=0;j<sistema->order;j++) {
        if(i != j)
          Xk[i] += A[i][j]*X[j];
      }

      Xk[i] = -Xk[i];
      Xk[i] += b[i];
      Xk[i] = Xk[i]/A[i][i];
    }

    iter++;    
    if(iter%100 == 0)
      fprintf(stderr,"Iter: %d\n",iter);

    if(iter >= sistema->MAX_ITER || parada(sistema->erro,X,Xk,sistema->order))
      continua = 0;
    
    swap(X,Xk,sistema->order);
  } while (continua);
  printf("Time calculating: %.10lf\n",(omp_get_wtime() - start_time)/60.0);

  printf("Finished in %d iterations\n",iter);
  printf("%.5lf = %.5lf\n",calculateLine(A,X,sistema->test_row,sistema->order),b[sistema->test_row]);

  return 0;
}

